package com.mybatis.boost.tool;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * @author jearton
 * @since 2016/12/17
 */
public abstract class StringUtil {

    @Nullable
    public static String trimAndToLowerCase(String s) {
        return s == null ? null : s.trim().toLowerCase();
    }

    @Nullable
    public static String trim(String s) {
        return s == null ? null : s.trim();
    }

    public static boolean isInteger(String text) {
        return text != null && trim(text).matches("^-?[1-9]\\d*$");
    }

    @Nonnull
    public static Integer parseInt(String text) {
        if (text == null) {
            throw new IllegalArgumentException("Text must not be null");
        }
        String trimmed = trim(text);
        return isHexNumber(trimmed) ? Integer.decode(trimmed) : Integer.valueOf(trimmed);
    }

    /**
     * Determine whether the given {@code value} String indicates a hex number,
     * i.e. needs to be passed into {@code Integer.decode} instead of
     * {@code Integer.valueOf}, etc.
     */
    public static boolean isHexNumber(String value) {
        int index = (value.startsWith("-") ? 1 : 0);
        return (value.startsWith("0x", index) || value.startsWith("0X", index) || value.startsWith("#", index));
    }
}
